package com.taotao.filter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.taotao.common.utils.DateUtil;
import com.taotao.common.utils.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSONObject;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.RedisUtils;


@Service
@Component
public class ApiFilter implements Filter {
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
			InputStream in;
			HashMap<String,String> resourceMap=new HashMap<>();
	        try{
	        	Properties prop = new Properties();     
	        	File file = ResourceUtils.getFile("classpath:/resource.properties");
	            in = new BufferedInputStream (new FileInputStream(file));
	            prop.load(in);     ///加载属性列表
	            Iterator<String> it=prop.stringPropertyNames().iterator();
	            while(it.hasNext()){
	            	String key=it.next();
		               resourceMap.put(key, prop.getProperty(key));
		               System.out.println(key+"--->"+prop.getProperty(key));
		            }
	        	in.close();
		        }catch (Exception e) {
					e.printStackTrace();
				}
	        String redis_use = resourceMap.get("redis_use");
	        if("true".equals(redis_use)){
	        	RedisUtils.init(resourceMap.get("redis_addr"), Integer.parseInt(resourceMap.get("redis_port")), resourceMap.get("redis_password"));
	        	RedisUtils.set(Constants.redisMap, JSONObject.toJSONString(resourceMap));
	        }
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
				HttpServletRequest httpRequest = (HttpServletRequest) request;
				String servletPath = httpRequest.getServletPath();
				
				String referer  = ((HttpServletRequest) request).getHeader("referer");
				//小程序网络请求的 referer 是不可以设置的，格式固定为：https://servicewechat.com/{appid}/{version}/page-frame.html
				if(servletPath.contains("/apiSecurityController")
						&& !referer.contains("servicewechat")){ //防盗链
					String ipAddress = IpUtil.getIPAddress((HttpServletRequest) request);
					System.out.println(DateUtil.getDateAndTime()+" ipAddress->"+ipAddress+" referer->"+referer +" servletPath->"+servletPath);
					return;
				}
				
				if(servletPath.contains(".")||servletPath.equals("/login")|| servletPath.equals("/loginOut")
						||servletPath.equals("/doLogin")||servletPath.contains("/redisLoad")||servletPath.contains("/page")
						||servletPath.contains("/api")){ //资源文件和登录登出相关的不校验session超时
					
					chain.doFilter(request, response);
				}else{
					String sessionId=(String) request.getParameter("sessionId");
					String userInfo = RedisUtils.get(sessionId);
					if(StringUtils.isBlank(userInfo)){
						RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login");
						requestDispatcher.forward(request, response);
						return ;
					}
					chain.doFilter(request, response);
					RedisUtils.expire(sessionId, Constants.redis_expire);
				}
	}

	@Override
	public void destroy() {
		System.out.println("destroy");
	}
}